<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">

    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="format-detection" content="telephone=no">
    <link rel="stylesheet" href="../../layui/css/layuilast.css" media="all">
    <link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.css">
</head>

<body>
    <div id="tabDIV" style="display: block">
        <div class="layui-row" style="margin-top: 3vh;">
            <div class="layui-inline">
                <label class="layui-form-label">账号</label>
                <div class="layui-input-inline">
                    <input type="text" id="bindUserLoginNo1" autocomplete="off" class="layui-input" placeholder="用户账号">
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">名称</label>
                <div class="layui-input-inline">
                    <input type="tel" id="bindRealName1" autocomplete="off" class="layui-input" placeholder="用户名称">
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">手机号</label>
                <div class="layui-input-inline">
                    <input type="tel" id="bindUserPhone1" autocomplete="off" class="layui-input" placeholder="用户手机号">
                </div>
            </div>

            <div class="layui-inline" style="float: right;margin-top: 1vh;margin-right: 1vh">
                <button class="layui-btn" onclick="reset()">
                    <i class="layui-icon layui-icon-delete"></i>清除
                </button>
                <button class="layui-btn" onclick="search()">
                    <i class="layui-icon layui-icon-search"></i>查询
                </button>
                <button id="btn-add" class="layui-btn">
                    <i class="layui-icon layui-icon-add-1"></i>新增
                </button>
            </div>
        </div>
        <table id="table" lay-filter="table"></table>
    </div>


    <div id="editForm" style="display: none;">
        <form id="updateForm" enctype="multipart/form-data">
            <div class="layui-card-body layui-form">
                <!-- <input type="hidden" name="username" id="id"> -->
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">登录账号</label>
                        <div class="layui-input-block">
                            <input id="bindUserLoginNo" type="text" disabled="disabled" name="username" autocomplete="off" class="layui-input" placeholder="填写登录账号" required="required">
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">登录密码</label>
                        <div class="layui-input-block">
                            <input type="password" name="password"id="password"  autocomplete="off" class="layui-input" placeholder="密码" required="required">
							<input type="checkbox" name="display" lay-filter="switchDisplay" title="显示密码" value="display">
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="realname" autocomplete="off" class="layui-input" placeholder="填写名称" required="required">
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">手机号</label>
                        <div class="layui-input-block">
                            <input type="text" name="phone" autocomplete="off" class="layui-input" placeholder="填写手机号" required="required">
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">绑定描述</label>
                        <div class="layui-input-block">
                            <input type="text" id="binddesc" name="binddesc" autocomplete="off" class="layui-input" placeholder="填写绑定描述" required="required">
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">头像</label>
                        <input type="hidden" id="headImg" name="upload">
                        <div class="layui-input-block">
                            <button type="button" class="layui-btn" id="upload_img">
                                <i class="layui-icon">&#xe67c;</i>选择图片
                            </button>
                            <span id="prompt"></span>
                            <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                                预览图：
                                <img class="headImg" width="100px" onclick="javascript:visitimg(this.src);">
                            </blockquote>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <div id="deviceListForm" style="display: none; height: 100%;margin-top: 30px;">
        <div class="layui-row" style="margin-top: 3vh;">

            <div class="layui-inline">
                <label class="layui-form-label">设备编号</label>
                <div class="layui-input-inline">
                    <input type="text" id="deviceMac1" autocomplete="off" class="layui-input" placeholder="设备编号">
                </div>
            </div>



            <div class="layui-inline" style="float: right;margin-top: 1vh;margin-right: 1vh">
                <button class="layui-btn" onclick="resetBind()">
                    <i class="layui-icon layui-icon-delete"></i>清除
                </button>
                <button class="layui-btn" onclick="searchBind()">
                    <i class="layui-icon layui-icon-search"></i>查询
                </button>
            </div>
        </div>
        <form class="layui-form" id="devBindForm" enctype="multipart/form-data">
            <table id="devListTable" lay-filter="devListTable"></table>
        </form>
    </div>

</body>


<script charset="utf-8" src="../../layui/js/jquery/jquery.js"></script>
<script charset="utf-8" src="../../layui/js/jquery/jquery.serializeJSON.js"></script>
<script charset="utf-8" src="../../layui/layuilast.js"></script>
<script charset="utf-8" src="../../layui/js/md5/md5.min.js"></script>
<script charset="utf-8" src="../../layui/js/extend/common.js"></script>
<!--<script src="../../js/http.js"></script>-->
<script type="text/javascript">
var  rootUrl=localStorage.getItem('rootUrl');
var pageAPI={
    pageURL:rootUrl+'/user/getSubAdminList'
}
console.log(rootUrl);
var pageDeviceURL =rootUrl+ "/device/getDeviceListByAdminAndSubAdmin";

    var url_add = "\/yk\/admin\/mita\/account\/addDeviceManger";
    var url_edit = "\/yk\/ykAdminDevManger\/updateBindUserInfo";
    var url_bind_device = "\/yk\/ykAdminDevManger\/bindAdminDevice";
    var url_unBind_device = "\/yk\/ykAdminDevManger\/unBindAdminDevice";
    var uploadURL = "\/yk\/file\/fileWebUpload";
    var tableId = "table";
    var selectUserId;
    let files='';
	var opUserId=1;
    var cols = [
        [
            {
                title: '序号',
                templet: '#indexTpl',
                width: 100
            },
            // {field: 'id',title: '用户ID', hide:false},
            {
                field: 'userName',
                title: '账号'
            },
            {
                field: 'realname',
                title: '名称'
            },
            {
                field: 'phone',
                title: '手机号'
            },
            {
                field: 'createtime',
                title: '创建时间',
                templet: function(d) {
                   return d.createtime==null?'':d.createtime.replace("T"," ").substring(0,19);
                }
            },
            {
                field: "bindDesc",
                title: '描述'
            },
            {
                field: "permitstate",
                title: '是否禁用',
                templet: '#isEnableStatus',
                width: 130
            },
            {
                toolbar: "#barDemo",
                align: 'center',
                title: '操作',
                width: 254,
                align: 'left'
            }
      
        ]
    ];


    function exclUser() {
        var usertType = $("#roleId").val().trim();
        window.location.href = "/leaseUser/downloadOrderUser?time==usertType" + usertType;
    }
    //表格数据初始化
    if(!localStorage.getItem('token')||!localStorage.getItem('userid')){
        window.location.href='../login/login.html'
    }else{
        // console.log('进来了',localStorage.getItem('token'));
        initTab(tableId, "#table", "table", pageAPI.pageURL, cols, {
            upuserid:localStorage.getItem('userid'),
            userid:localStorage.getItem('userid'),
            token:localStorage.getItem('token')
        },null,null)
    }

    function reset() {
        /*$("#bindUserLoginNo1").val("");
        $("#bindRealName1").val("");
        $("#bindUserPhone1").val("");*/
		window.location.reload();
    }

    function resetBind() {
        $("#deviceMac1").val("");

    }

    function searchBind() {
        var table = layui.table;

        var deviceMac = $("#deviceMac1").val().trim();
        table.reload("devListTable", {
            page: {
                curr: 1
            },
            where: {
                deviceMac: deviceMac
            },
        });
    }
    //条件查询
    function search() {
        var table = layui.table;

		var url=rootUrl+"/user/getSubAdminListByNameAndPhoneAndUpUser";
		var username = $("#bindUserLoginNo1").val().trim();
		var realname = $("#bindRealName1").val().trim();
		var phone = $("#bindUserPhone1").val().trim();
		console.log(username+" : "+localStorage.getItem('userid'));
		initTab(tableId, "#table", "table", url, cols, {
			username: username,
			realname: realname,
			phone: phone,
			upuserid:localStorage.getItem('userid'),
		    userid:localStorage.getItem('userid'),
		    token:localStorage.getItem('token')
		},null,null)
        
    }

    //新增
    $("#btn-add").click(function() {
        $("#updateForm")[0].reset();
        $(".headImg").prop("src", "");
        // $("#id").val("");
        $("#bindUserLoginNo").attr("disabled", false);
        openEditForm('add');
    });
    //打开编辑框
    function openDevEditForm() {
        layer.open({
            type: 1,
            skin: 'layui-layer-demo', //样式类名
            // skin: 'layui-layer-rim', //加上边框
            area: ['90%', '90%'], //宽高
            anim: 2,
            shadeClose: true, //开启遮罩关闭,
            maxmin: true,
            title: "设备分配列表",
            content: $("#deviceListForm"),
            btn: ['关闭'],
            no: function(index, layero) {


            }
        });
    }

function visitimg(src) {

        var img = new Image();  
        img.src = src;
        var imgHtml = "<img src='" + src + "' width='500px' height='500px'/>";  
		console.log("visitimg");
        //弹出层
        layer.open({  
            type: 1,  
            shade: 0.8,
            offset: 'auto',
            area: [500 + 'px',550+'px'],
            shadeClose:true,
            scrollbar: false,
            title: "图片预览", //不显示标题  
            content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响  
            cancel: function () {  
                //layer.msg('捕获就是从页面已经存在的元素上，包裹layer的结构', { time: 5000, icon: 6 });  
            }  
        }); 
    }

    //打开编辑框
    function openEditForm(type,obuserid) {
        $('#prompt').text('')
        layer.open({
            type: 1,
            skin: 'layui-layer-demo', //样式类名
            area: ['80%', '80%'], //宽高
            anim: 2,
            shadeClose: true, //开启遮罩关闭,
            maxmin: true,
            title: "编辑信息",
            content: $("#editForm"),
            btn: ['提交','关闭'],
            yes: function(index, layero) {
                const data = $('#updateForm').getData();
                const formData = new FormData($( "#updateForm" )[0]);  
                for (var key in data) {
                    var element = data[key];
                    if ( key != "password" && key !='upload') {
                        console.log("key->" + key + "  element = " + element)
                        if (element == null || element == '' || element == undefined) {
                            layer.alert("表单数据没有填写完全!");
                            return;
                        }
                    }
                }
            
                formData.append('upload',files)
                formData.append('token',localStorage.getItem('token')),
                formData.append('userid',localStorage.getItem('userid'))
                switch (type){
                    case 'add':
                        let val=$("input[name=password]").val();
                        console.log('查看添加的值',val);
                    if(val==''||files==''){
                        layer.alert("表单数据没有填写完全!");
                            return;
                    }
					 $.ajax({
            url: rootUrl+"/user/addSubAdministator",
            asynnc:false,
            cache:false,            
            data: formData,
            dataType: 'json',
            contentType: false,
             processData: false,
            type: 'post',
            success: function(res){
                if (res.errorcode == 0) {
				layer.msg(res.resultmsg);
                    location.reload();
                }else{
                   layer.msg(res.resultmsg);
                }
				
            },
            error: function(res) {
                // 服务器繁忙
                alert('服务器繁忙');
            },

        });
                                  
                            break;
                    case 'edit':
					//console.log("obuserid:"+obuserid);
					
                    formData.append('obuserid',obuserid)
                    if(files===''){
                       // layer.msg('请重新上传头像');
					   $.ajax({
					       url: rootUrl+"/user/modifySubAdministatorNoPic",
					       asynnc:false,
					       cache:false,            
					       data: formData,
					       dataType: 'json',
					       contentType: false,
					        processData: false,
					       type: 'post',
					       success: function(res){
					           if (res.errorcode == 0) {
					   		layer.msg(res.resultmsg);
					               location.reload();
					           }else{
					              layer.msg(res.resultmsg);
					           }
					       },
					       error: function(res) {
					           // 服务器繁忙
					           alert('服务器繁忙');
					       },
					   });
                        return true;
                    }
					 $.ajax({
            url: rootUrl+"/user/modifySubAdministator",
            asynnc:false,
            cache:false,            
            data: formData,
            dataType: 'json',
            contentType: false,
             processData: false,
            type: 'post',
            success: function(res){
                if (res.errorcode == 0) {
				layer.msg(res.resultmsg);
                    location.reload();
                }else{
                   layer.msg(res.resultmsg);
                }
				
            },
            error: function(res) {
                // 服务器繁忙
                alert('服务器繁忙');
            },

        });
                }    
            }
        });
    }
    layui.use(['table', 'form', 'upload'], function() {
        var table = layui.table;
        var form = layui.form();
        var upload = layui.upload;
        //监听多选框点击事件  主要是通过 lay-filter="switchTest"  来监听
        form.on('checkbox(switchDisplay)', function (data) {
        　　console.log( data );　　//打印当前选择的信息
		var showPwd=$("#password");
            if( data.elem.checked){　　　　　　//判断当前多选框是选中还是取消选中
                showPwd.prop('type','text');
            }
			else
			  {
				  showPwd.prop('type','password');
			  }
        　　var value = data.value;   //获取选中的value值
        });
         

        //上传图片
        upload.render({
            elem: '#upload_img',
            url: uploadURL,
            choose: function(res) {
                //上传完毕回调
                    //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
                    res.preview(function(index, file, result){
                    console.log(index); //得到文件索引
                    console.log('文件对象',file); //得到文件对象
                   // console.log(result); //得到文件base64编码，比如图片
                    $("#prompt").text(file.name);
                    $("#headImg").val(file);
                    files=file
                    $(".headImg").prop("src", result);
                    });
            },
        });//end render


        //删除和修改
        table.on('tool(table)', function(obj) {
            var data = obj.data;
            if (obj.event === 'del') { //删除
                layer.confirm('真的删除行么', function(index) {
                    $.post(delURL, {
                        id: data.id
                    }, function(resp) {
                        if (resp.success) {
                            window.location.reload();
                        }
                        console.info(resp.info);
                    })
                    layer.close(index);
                    $("#query-btn").click();
                });
            } else if (obj.event === 'edit') {
                // console.log(data);
                $('#updateForm').loadData(data);
                //$(".headImg").prop("src", data.avatarurl);
                // files=data.avatarurl
                $("#id").val(data.id);
                $("input[name=password]").val(data.password);
                $("#bindUserLoginNo").val(data.userName);
                $("#binddesc").val(data.bindDesc);
                $("#bindUserLoginNo").attr("disabled", true);
				$(".headImg").prop("src", rootURL+data.avatarurl);
				
                form.render();
                openEditForm('edit',data.userId);
            }else if (obj.event === 'delete') {
                var tableId = "devListTable";
               var obuserid=obj.data.userId;
			   $.ajax({
			       url: rootUrl+"/user/deleteUser",
			       asynnc:false,
			       cache:false,            
			       data: {
			   	obuserid:obuserid,
			   	
			   	userid:localStorage.getItem('userid'),
			       token:localStorage.getItem('token')
			   	},
			       dataType: 'json',
			      
			       type: 'post',
			       success: function(res){
			           if (res.errorcode == 0) {
			   		layer.msg(res.resultmsg);
			               location.reload();
			           }else{
			              layer.msg(res.resultmsg);
			           }
			   		
			       },
			       error: function(res) {
			           // 服务器繁忙
			           alert('服务器繁忙');
			       },
			   
			   });//end ajax
            } else if(obj.event === 'deviceManger') {
                var tableId = "devListTable";
               opUserId=obj.data.userId;
			   console.log(opUserId);
                var cols = [
                    [
                        {
                            title: '序号',
                            templet: '#indexTpl',
                            width: 50
                        },
                        // {field: 'id',title: '用户ID', hide:false},
                        // {field: 'phone', title: '手机号'},
                        // {field: 'userName', title: '用户名'},
                        {
                            field: 'deviceSn',
                            title: '设备编号'
                        },
                        {
                            field: 'addTime',
                            title: '绑定管理时间',
                            templet: function(d) {
                                if (d.updatetime != null && d.updatetime != undefined) {
                                    return d.updatetime.replace("T"," ").substring(0,19);
                                } else {
                                    return "未绑定管理";
                                }

                            }
                        },
                        {
                            field: 'deviceDesc',
                            title: '设备描述'
                        },
                        {
                            field: 'adminName',
                            title: '设备管理人'
                        },
                        {
                            field: "adminPhone",
                            title: '管理人手机'
                        },
                            {
                            field: "address",
                            title: '设备地址'
                        },
                        {
                            field: "city",
                            title: '设备所在城市'
                        },
                        {
                            toolbar: "#operation",
                            align: 'center',
                            title: '操作',
                            width: 154,
                            align: 'left'
                        }
                    ]
                ];
             console.log(pageDeviceURL);
                
                //表格数据初始化
                initTab(tableId, "#devListTable", "devListTable", pageDeviceURL, cols, {
                    adminuserid:opUserId,
                    userid:localStorage.getItem('userid'),
                    token:localStorage.getItem('token')
                }, null);
                openDevEditForm();
            }//end else
            
        });//end on


        table.on('tool(devListTable)', function(obj) {
            var data = obj.data;
			console.log(data);
            if (obj.event === 'dist') {

                // data.userId=selectUserId;
                var bindData = {};
                bindData.userId = selectUserId;
                bindData.deviceMac = data.deviceMac;
				console.log(opUserId);
                console.log("--------->" + JSON.stringify(data))
				 $.ajax({
            url: rootUrl+"/device/modifyDeviceAdmin",
            asynnc:false,
            cache:false,            
            data: {
			deviceid:data.deviceId,
			adminuserid:opUserId,
			
			userid:localStorage.getItem('userid'),
            token:localStorage.getItem('token')
			},
            dataType: 'json',
           
            type: 'post',
            success: function(res){
                if (res.errorcode == 0) {
				layer.msg(res.resultmsg);
                    //location.reload();
					table.reload('devListTable');
                }else{
                   layer.msg(res.resultmsg);
                }
				
            },
            error: function(res) {
                // 服务器繁忙
                alert('服务器繁忙');
            },

        });
                
            } else if (obj.event === 'undist') {
			 $.ajax({
            url: rootUrl+"/device/modifyDeviceAdmin",
            asynnc:false,
            cache:false,            
            data: {
			deviceid:data.deviceId,
			adminuserid:localStorage.getItem('userid'),
			
			userid:localStorage.getItem('userid'),
            token:localStorage.getItem('token')
			},
            dataType: 'json',
           
            type: 'post',
            success: function(res){
                if (res.errorcode == 0) {
				layer.msg(res.resultmsg);
                   table.reload('devListTable');
                }else{
                   layer.msg(res.resultmsg);
                }
				
            },
            error: function(res) {
                // 服务器繁忙
                alert('服务器繁忙');
            },

        });
              

            }//end else



        })//end table.on
              
        // //启用禁用开关
        form.on('switch(isEnable)', function (obj) {
             var isDelete;
            var tips;
           var title;
		   //console.log(obj.value)
           	if(obj.value==1)
			{
			layer.msg('超级管理员不能禁用!');
			return;
			}
             if (obj.elem.checked) {
              
				  title="确定禁用";
                tips="确定禁用用户吗";
                 isDelete =1;
            } else {
                 isDelete = 0;
                 title="确定启用";
                 tips="确定启用用户吗";
            }
            layer.confirm(tips, {title: title}, function (index) {
                 var id = obj.value;
                 layer.close(index);
				 
				 $.ajax({
            url: rootUrl+"/user/setUserPermit",
            asynnc:false,
            cache:false,            
            data: {
			obuserid:id,
			permitstate:isDelete,
            userid:localStorage.getItem('userid'),
            token:localStorage.getItem('token')
			},
            dataType: 'json',
            
            type: 'post',
            success: function(res){
                if (res.errorcode == 0) {
				layer.msg(res.resultmsg);
                    //location.reload();
                }else{
                   layer.msg(res.resultmsg);
                }
				
            },
            error: function(res) {
                // 服务器繁忙
                alert('服务器繁忙');
            },

        });
                   
                
             });//end confirm
         });//end on

    });//end use
</script>


<!--table的序号-->
<script type="text/html" id="indexTpl">
{{d.LAY_TABLE_INDEX+1}}
</script>

<!-- 启用禁用开关-->
<script type="text/html" id="isEnableStatus">
{{# if(d.permitstate == 1){ }}
    <input type="checkbox"  value="{{d.userId}}" lay-skin="switch" lay-text="是|否" lay-filter="isEnable" checked="checked" />
    {{# }else if(d.permitstate==0){ }}
        <input type="checkbox"  value="{{d.userId}}" lay-skin="switch" lay-text="是|否" lay-filter="isEnable" />
        {{# } }}
</script>

<!--table的操作按钮-->
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
		<a class="layui-btn layui-btn-xs" lay-event="delete">删除</a>
		<a class="layui-btn layui-btn-xs " lay-event="deviceManger">设备管理</a>
</script>
<!--table的操作按钮-->
<script type="text/html" id="operation">
{{# if(d.adminUserId != opUserId){ }}
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="dist">分配</a>
    {{# }else if(d.adminUserId==opUserId){ }}
        <a class="layui-btn layui-btn-xs " lay-event="undist">取消</a>
        {{# } }}
</script>

</html>